package com.weipeep.sys.service.impl;

import com.weipeep.common.utils.DateUtils;
import com.weipeep.sys.domain.SignInDo;
import com.weipeep.sys.query.SignQuery;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.weipeep.sys.dao.SignDao;
import com.weipeep.sys.domain.SignDO;
import com.weipeep.sys.service.SignService;
import com.weipeep.common.base.CoreServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2018-04-16 21:15:48 | wangyun</small>
 */
@Service
public class SignServiceImpl extends CoreServiceImpl<SignDao, SignDO> implements SignService {
    @Autowired
    SignDao signDao;
    @Override
    @Transactional
    public boolean signOrOut(Long userId, Integer signType) {
        SignDO signDO = null;
        SignQuery signQuery = new SignQuery();
        signQuery.setUserId(userId);
        signQuery.setBeginTime(DateUtils.getStartTime());
        signQuery.setEndTime(DateUtils.getEndTime());
        List<SignDO> signDOList = signDao.selectTodyList(signQuery);
        if (signDOList !=null && signDOList.size()>0){
            signDO = signDOList.get(0);
        }else {
            signDO = new SignDO();
            signDO.setUserId(userId);
            signDO.setCreateTime(DateUtils.now());
        }
        if(signType==1){
            if (signDO.getSignInTime()==null){
                signDO.setSignInTime(DateUtils.now());
            }
        }else if(signType==2){
            signDO.setSignOutTime(DateUtils.now());
        }
        if (signDO.getId()!=null){
            baseMapper.updateById(signDO);
        }else {
            baseMapper.insert(signDO);
        }
        return true;
    }

    @Override
    public Map<Long, SignDO> fetchSigned(Date beginTime, Date endTime) {
        SignQuery signQuery = new SignQuery();
        signQuery.setBeginTime(beginTime);
        signQuery.setEndTime(endTime);
        List<SignDO> signDOList = signDao.selectTodyList(signQuery);
        Map<Long,SignDO> map = signDOList.stream().collect(
                Collectors.toMap(SignDO::getUserId,signDO -> signDO));
        return map;
    }

    @Override
    public List<SignInDo> getSignInList(Date beginTime, Date endTime) {
        SignQuery signQuery = new SignQuery();
        signQuery.setBeginTime(beginTime);
        signQuery.setEndTime(endTime);
        List<SignInDo> list = signDao.getSignInList(signQuery);
        return list;
    }
}
